import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { localRead, setTitle } from '@/utils'
import { getToken, setToken } from '@/utils/auth'
import config from '@/config'

const { homeName } = config

Vue.use(Router)

const LOGIN_PAGE_NAME = 'login'

const beforeEachHandler = (to, from, next) => {
  iView.LoadingBar.start()

  if (to.name === 'error_404' && !store.state.loaded) {
    const ctrl = setInterval(() => {
      if (store.state.loaded) {
        clearInterval(ctrl)
        router.push(to.path)
      }
    }, 50)
    return
  }

  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    if (store.state.user.hasGetInfo) {
      next()
    } else {
      if (localRead('userInfo')) {
        next()
      } else {
        setToken('')
        next({
          name: 'login'
        })
      }
    }
  }
}

const afterEachHandler = (to) => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
}

const createRouter = () =>
  new Router({
    mode: 'history',
    routes: routes
  })

const router = createRouter()

router.beforeEach(beforeEachHandler)
router.afterEach(afterEachHandler)

export function resetRouter() {
  const newRouter = createRouter()

  newRouter.beforeEach(beforeEachHandler)
  newRouter.afterEach(afterEachHandler)
  router.matcher = newRouter.matcher
}

export default router
